<template>
    <van-sticky>
        <van-nav-bar title="邮箱认证" left-text="返回" left-arrow @click-left="onBack" />
    </van-sticky>

    <div class="user">
        <div class="user-image">
            <img :src="business.avatar_cdn" />
        </div>
    </div>
    <van-form @submit="onSubmit">
        <van-field v-model="business.email" name="email" label="邮箱" placeholder="请输入邮箱" readonly :rules="[
            { required: true, message: '请输入邮箱' },
            { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确' }
        ]" />

        <van-field v-model="code" name="code" center clearable label="验证码" placeholder="请输入短信验证码" :rules="[
            { required: true, message: '请输入短信验证码' }
        ]">
            <template #button>
                <van-button size="small" type="primary" @click="onSend" :disabled="disabled">{{ msg }}</van-button>
            </template>
        </van-field>

        <div style="width:50%;margin:2em auto;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>
<script setup>
import { setTransitionHooks } from 'vue';


const { proxy } = getCurrentInstance();

const business = proxy.$business;
const code = ref('');
const disabled = ref(false);
//验证码倒计时
const msg = ref('获取验证码');
// const time = ref(60);

const onSubmit = async (values) =>
{
    values.id = business.value.id;

    let result = await proxy.$http.post({
        url:'/business/email',
        params:values
    })

    if(result.code === 1)
    {
        proxy.$success({
            message:result.msg,
            onClose:() =>
            {
                onBack();
            }
        });
    }else{
        proxy.$warning(result.msg);
    }
}
const onSend = async () =>
{
    let params = {
        id:business.value.id,
        email:business.value.email
    }

    disabled.value = true;

    let result = await proxy.$http.post({
        url:'/business/send',
        params
    })

    CountDown();

    if(result.code === 1)
    {
        proxy.$success(result.msg);
    }else{
        proxy.$warning(result.msg);
    }
}

const CountDown = () =>
{
    let time = 60;
    
    let timer = setInterval(() => {

        if(time === 1)
        {
            msg.value = '重新发送验证码';

            disabled.value = false;

            clearInterval(timer);

            return false;
        }

        time--;

        msg.value = `${time}秒后重新发送`;

        
    },1000);
}

const onBack = () => proxy.$router.back();

</script>

<style scoped>
@import url('/assets/css/BusinessProfile.css');
</style>